package org.black.phoneUtility.sms.schedule.app.fragment;

import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.schedule.provider.SmsScheduleContract;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.MenuItem;

public class SmsSchedulePreferenceFragment extends PreferenceFragment implements
		SharedPreferences.OnSharedPreferenceChangeListener {
	private static final String LOG_TAG = SmsSchedulePreferenceFragment.class
			.getName();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.sms_schedule_perference);

		Log.i(LOG_TAG, "Load R.xml.sms_schedule_perference.");

		getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences()
				.unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getActivity().onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals(getString(R.string.preference_sms_schedule_do_not_send_schedule_message_on_roaming)) == true) {
			boolean doNotSendSmsScheduleMessage = sharedPreferences.getBoolean(
					key, true);
			ContentValues doNotSendSmsSeheduleContentValues = new ContentValues();
			doNotSendSmsSeheduleContentValues
					.put(SmsScheduleContract.SmsScheduleGlobalSettings.DO_NOT_SEND_SCHEDULE_MESSAGE_ON_ROAMING,
							true == doNotSendSmsScheduleMessage ? 1 : 0);
			getActivity()
					.getContentResolver()
					.update(ContentUris.withAppendedId(
							SmsScheduleContract.SmsScheduleGlobalSettings.CONTENT_URI,
							1l), doNotSendSmsSeheduleContentValues, null,
							null);
		}

	}

}
